package com.j180.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.j180.bean.Customer;
import com.j180.bean.ResultBean;
import com.j180.service.CustomerServiceImpl;
import com.j180.service.ICustomerService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "AddServlet",value = "/add")
public class AddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决乱码
        request.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //接受参数
        String name = request.getParameter("cname");
        String address = request.getParameter("address");

        Customer customer = new Customer();
        customer.setCname(name);
        customer.setAddress(address);

        ICustomerService iCustomerService = new CustomerServiceImpl();

        int result =  iCustomerService.addCustomerInfo(customer);

        ResultBean resultBean = null;
        if(result==1){
            resultBean = new ResultBean(1,1,"添加成功");
        }else{
            resultBean = new ResultBean(0,0,"添加失败");
        }

        ObjectMapper objectMapper =new ObjectMapper();

        response.getWriter().print(objectMapper.writeValueAsString(resultBean));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          doPost(request,response);
    }
}
